package com.dennytech.tac.ui.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import pl.polidea.sectionedlist.SectionListAdapter;
import pl.polidea.sectionedlist.SectionListItem;
import pl.polidea.sectionedlist.SectionListView;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.dennytech.tac.R;
import com.dennytech.tac.base.BasicAdapter;
import com.dennytech.tac.base.CFListActivity;
import com.dennytech.tac.model.Record;
import com.dennytech.tac.statistics.Stat;
import com.dennytech.tac.utils.CFUtils;
import com.dennytech.tac.utils.Daemon;
import com.dennytech.tac.utils.PhotoPicker;
import com.dennytech.tac.utils.db.TimelineDBHelper;
import com.dennytech.tac.widget.LocalImageView;
import com.google.android.photostream.UserTask;

public class TimelineActivity extends CFListActivity implements
		OnItemClickListener, OnItemLongClickListener {

	private static final int REQUEST_CODE_ADD_RECORD = 1;

	private PhotoPicker photoPicker;

	private Adapter adapter;
	private SectionListAdapter sectionAdapter;
	private Task task;

	private int currentLongClickItem = -1;

	@Override
	protected void initView() {
		setContentView(R.layout.layout_timeline);
		listView = (SectionListView) findViewById(R.id.list);
	}

	@Override
	protected void setEmptyView() {
		super.setEmptyView();
	}

	protected void setEmptyView(View view) {
		emptyView = (FrameLayout) view.findViewById(R.id.empty);
		listView.setEmptyView(emptyView);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle(getResources().getString(R.string.tab_name_timeline));

		photoPicker = new PhotoPicker(this);

		adapter = new Adapter();
		sectionAdapter = new SectionListAdapter(getLayoutInflater(), adapter);
		listView.setAdapter(sectionAdapter);

		sectionAdapter.setOnItemClickListener(this);
		listView.setOnItemClickListener(sectionAdapter);

		sectionAdapter.setOnItemLongClickListener(this);
		listView.setOnItemLongClickListener(sectionAdapter);

		refresh();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("Camera")
				.setIcon(R.drawable.ic_camera)
				.setShowAsAction(
						MenuItem.SHOW_AS_ACTION_ALWAYS
								| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if ("Camera".equals(item.getTitle())) {
			photoPicker.doTakePhoto();
			Stat.event("timeline", "timeline_titlebtn", null, 0);
		}
		return super.onOptionsItemSelected(item);
	}

	private void refresh() {
		if (task != null) {
			task.cancel(true);
		}

		task = new Task();
		task.execute();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (currentLongClickItem != -1) {
			return;
		}

		Intent i = new Intent(Intent.ACTION_VIEW,
				Uri.parse("denny://addrecord"));
		i.putExtra("record", (Record) adapter.getItem(position).item);
		startActivityForResult(i, REQUEST_CODE_ADD_RECORD);

		Stat.event("timeline", "timeline_item_click", String.valueOf(position),
				0);
	}

	@Override
	public boolean onItemLongClick(final AdapterView<?> parent,
			final View view, final int position, final long id) {
		Stat.event("timeline", "timeline_item_longclick",
				String.valueOf(position), 0);

		startActionMode(new AnActionModeOfEpicProportions());
		currentLongClickItem = position;

		return false;
	}

	private final class AnActionModeOfEpicProportions implements
			ActionMode.Callback {
		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {

			menu.add(getString(R.string.timeline_menu_send))
					.setIcon(R.drawable.ic_backup)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			menu.add(getString(R.string.timeline_menu_delete))
					.setIcon(R.drawable.ic_delete)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			if (getString(R.string.timeline_menu_view).equals(item.getTitle())) {
				Intent i = new Intent(Intent.ACTION_VIEW,
						Uri.parse("denny://addrecord"));
				i.putExtra("record",
						(Record) adapter.getItem(currentLongClickItem).item);
				startActivityForResult(i, REQUEST_CODE_ADD_RECORD);

				Stat.event("timeline", "timeline_item_view", null, 0);

			} else if (getString(R.string.timeline_menu_send).equals(
					item.getTitle())) {
				Record record = (Record) adapter.getItem(currentLongClickItem).item;
				Intent returnIt = new Intent(Intent.ACTION_SEND);
				String[] tos = { "" };
				returnIt.putExtra(Intent.EXTRA_EMAIL, tos);
				returnIt.putExtra(Intent.EXTRA_TEXT, record.getIntro());
				returnIt.putExtra(
						Intent.EXTRA_SUBJECT,
						getString(R.string.timeline_send_subject)
								+ " , "
								+ CFUtils.dateToString(record.getDate(),
										"MMMM dd, yyyy"));
				Uri uri = Uri.parse("file://" + record.getImage());
				returnIt.putExtra(Intent.EXTRA_STREAM, uri);
				returnIt.setType("image/*");
				returnIt.setType("message/rfc882");
				Intent.createChooser(returnIt,
						getString(R.string.timeline_send_choose_title));
				startActivity(returnIt);

				Stat.event("timeline", "timeline_item_sendcopy", null, 0);

			} else if (getString(R.string.timeline_menu_delete).equals(
					item.getTitle())) {
				new Handler(Daemon.looper()) {
					public void handleMessage(android.os.Message msg) {
						TimelineDBHelper helper = TimelineDBHelper.instance();
						if (helper.delete((Record) adapter
								.getItem(currentLongClickItem).item) > 0) {
							Toast.makeText(
									TimelineActivity.this,
									getResources().getString(
											R.string.message_delete_success),
									Toast.LENGTH_SHORT).show();
							refresh();
						}
					};
				}.sendEmptyMessage(0);

				Stat.event("timeline", "timeline_item_delete", null, 0);
			}

			mode.finish();
			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
			currentLongClickItem = -1;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == PhotoPicker.REQUEST_CODE_CAMERA) {
			String strImgPath = photoPicker.strImgPath();
			if (!TextUtils.isEmpty(strImgPath)) {
				File f = new File(strImgPath);
				if (!f.exists()) {
					strImgPath = photoPicker.parseImgPath(data);
				}

			} else {
				strImgPath = photoPicker.parseImgPath(data);
			}
			if (!TextUtils.isEmpty(strImgPath)) {
				Intent i = new Intent(Intent.ACTION_VIEW,
						Uri.parse("denny://addrecord?image=" + strImgPath));
				startActivityForResult(i, REQUEST_CODE_ADD_RECORD);
			}
		} else if (requestCode == REQUEST_CODE_ADD_RECORD) {
			if (resultCode == Activity.RESULT_OK) {
				refresh();
			}

		}
	}

	class Task extends UserTask<String, Void, List<Record>> {

		@Override
		public List<Record> doInBackground(String... params) {
			TimelineDBHelper helper = TimelineDBHelper.instance();
			return helper.query();
		}

		@Override
		public void onPostExecute(List<Record> result) {
			adapter.setData(result);
			sectionAdapter.notifyDataSetChanged();
		}

	}

	class Adapter extends BasicAdapter {

		private List<SectionListItem> data = new ArrayList<SectionListItem>();

		public void setData(List<Record> d) {
			data.clear();

			if (d == null) {
				sectionAdapter.updateSessionCache();
				notifyDataSetChanged();
				return;
			}

			for (Record record : d) {
				SectionListItem section = new SectionListItem(record,
						CFUtils.dateToString(record.getDate(), "MMMM yyyy"));
				data.add(section);
			}
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			if (data == null) {
				return 0;
			}
			return data.size();
		}

		@Override
		public SectionListItem getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
				view = LayoutInflater.from(parent.getContext()).inflate(
						R.layout.timeline_list_item, parent, false);
			}
			SectionListItem item = getItem(position);
			Record ta = (Record) item.item;

			LocalImageView liv = (LocalImageView) view.findViewById(R.id.photo);
			liv.setImage(ta.getImage());

			TextView introTv = (TextView) view.findViewById(R.id.intro);
			if (TextUtils.isEmpty(ta.getIntro())) {
				introTv.setVisibility(View.INVISIBLE);
			} else {
				introTv.setText(ta.getIntro());
				introTv.setVisibility(View.VISIBLE);
			}

			TextView dateTv = (TextView) view.findViewById(R.id.date);
			dateTv.setText(CFUtils.dateToString(ta.getDate(), "MMMM dd, yyyy"));

			return view;
		}

	}

}
